//
//  ZPCircleScrollView.m
//  ZhenPin
//
//  Created by 董伟1 on 16/4/5.
//  Copyright © 2016年 zhenpin. All rights reserved.
//

#import "ZPCircleScrollView.h"

#define PictureDefaultTag 100000

@interface ZPCircleScrollView ()
{
    UIScrollView  *picScrollView;
    UIPageControl  *pageControl;
    NSTimer  *scrollTimer;
    NSArray  *showPicArr;
    
    NSInteger  allPage;
}

@end

@implementation ZPCircleScrollView

- (id)initWithFrame:(CGRect)frame
{
    self = [super  initWithFrame:frame];
    if (self) {
        
        [[NSNotificationCenter  defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];
        [[NSNotificationCenter  defaultCenter] addObserver:self selector:@selector(applicationWillEnterForeground) name:UIApplicationWillEnterForegroundNotification object:nil];
        
        self.backgroundColor = [UIColor  colorWithRed:238/255. green:238/255. blue:238/255. alpha:1.];
        
        picScrollView = [[UIScrollView  alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
        picScrollView.showsHorizontalScrollIndicator = NO;
        picScrollView.showsVerticalScrollIndicator = NO;
        picScrollView.contentSize = CGSizeMake(frame.size.width, frame.size.height);
        picScrollView.delegate = self;
        picScrollView.pagingEnabled = YES;
        picScrollView.backgroundColor = [UIColor  clearColor];
        [self  addSubview:picScrollView];
        
        pageControl = [[UIPageControl  alloc] initWithFrame:CGRectMake(frame.size.width - 100, frame.size.height - 30, 100, 30)];
        pageControl.numberOfPages = 0;
        pageControl.pageIndicatorTintColor = [UIColor  colorWithRed:254/255. green:242/255. blue:188/255. alpha:1.];
        pageControl.currentPageIndicatorTintColor = [UIColor  colorWithRed:158/255. green:224/255. blue:252/255. alpha:1.];
        pageControl.currentPage = 0;
        [self  addSubview:pageControl];
        
        allPage = 0;
        
    }
    
    return self;
}

- (void)reloadViewWithArray:(NSArray *)array
{
    if (!array) {
        return;
    }
    
    if (array.count == 1) {
        pageControl.hidden = YES;
    }else {
        pageControl.hidden = NO;
    }
    showPicArr = array;
    
    //循环滚动图片
    for (UIImageView  *tempImv in picScrollView.subviews) {
        [tempImv  removeFromSuperview];
    }
    if (scrollTimer) {
        [scrollTimer  invalidate];
        scrollTimer = nil;
    }
    NSInteger  picCount = array.count;
    allPage = picCount;
    pageControl.numberOfPages = allPage;
    if (showPicArr && picCount > 0) {
        CGFloat  scrollWidth = picScrollView.frame.size.width;
        CGFloat  scrollHeight = picScrollView.frame.size.height;
        if (picCount == 1) {
            picScrollView.contentSize = CGSizeMake(scrollWidth, scrollHeight);
            picScrollView.scrollEnabled = NO;
        }else{
            picScrollView.contentSize = CGSizeMake(scrollWidth*(picCount+2), scrollHeight);
            picScrollView.scrollEnabled = YES;
        }
        for (int i = 0; i < picCount; i ++) {
            NSDictionary  *tempDic = [showPicArr  objectAtIndex:i];
            
            UIImageView  *imageView = [[UIImageView  alloc] initWithFrame:CGRectMake(scrollWidth + scrollWidth * i, 0, scrollWidth, scrollHeight)];
            imageView.contentMode = UIViewContentModeScaleAspectFill;
            imageView.clipsToBounds = YES;
            [imageView  sd_setImageWithURL:[NSURL URLWithString:[tempDic  objectForKey:@"imgUrl"]] placeholderImage:[UIImage imageNamed:@"noimage1"] options:SDWebImageProgressiveDownload|SDWebImageRetryFailed];
            imageView.tag = PictureDefaultTag + i;
            imageView.userInteractionEnabled = YES;
            UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(topPicSingleTapAction:)];
            [imageView addGestureRecognizer:singleTap];
            [picScrollView  addSubview:imageView];
            
//            NSString *nameStr = [tempDic  objectForKey:@"title"];
//            if (![nameStr  isEqual:[NSNull  null]] && ![nameStr  isEqual:@""]) {
//                UIImageView  *shadowImv = [[UIImageView  alloc] initWithFrame:CGRectMake(0, imageView.frame.size.height - 54, imageView.frame.size.width, 54)];
//                shadowImv.userInteractionEnabled = YES;
//                shadowImv.image = [UIImage  imageNamed:@"home_circle_shadow"];
//                [imageView  addSubview:shadowImv];
//                
//                UILabel  *shadowLab = [[UILabel  alloc] initWithFrame:CGRectMake(10, 25, shadowImv.frame.size.width - 20, 20)];
//                shadowLab.text = [tempDic  objectForKey:@"title"];
//                shadowLab.font = [UIFont  systemFontOfSize:14.];
//                shadowLab.textColor = [UIColor  whiteColor];
//                shadowLab.textAlignment = NSTextAlignmentCenter;
//                [shadowImv  addSubview:shadowLab];
//            }
            
        }
        
        //取数组最后一张图片 放在第0页 取数组第一张图片 放在最后1页
        for (int i = 0; i < 2; i ++) {
            UIImageView  *imageView = [[UIImageView  alloc] initWithFrame:CGRectMake(scrollWidth * (picCount + 1) * i, 0, scrollWidth, scrollHeight)];
            imageView.contentMode = UIViewContentModeScaleAspectFill;
            imageView.clipsToBounds = YES;
            
            
            NSDictionary  *tempDic = nil;
            if (i == 0) {
                tempDic = [showPicArr  objectAtIndex:picCount-1];
                imageView.tag = PictureDefaultTag + (picCount-1);
                
            }else{
                tempDic = [showPicArr  objectAtIndex:0];
                imageView.tag = PictureDefaultTag;
            }
            
            [imageView  sd_setImageWithURL:[NSURL URLWithString:[tempDic  objectForKey:@"imgUrl"]] placeholderImage:[UIImage imageNamed:@"noimage1"] options:SDWebImageProgressiveDownload|SDWebImageRetryFailed];
            
//            NSString *nameStr = [tempDic  objectForKey:@"title"];
//            if (![nameStr  isEqual:[NSNull  null]] && ![nameStr  isEqual:@""]) {
//                UIImageView  *shadowImv = [[UIImageView  alloc] initWithFrame:CGRectMake(0, imageView.frame.size.height - 54, imageView.frame.size.width, 54)];
//                shadowImv.userInteractionEnabled = YES;
//                shadowImv.image = [UIImage  imageNamed:@"home_circle_shadow"];
//                [imageView  addSubview:shadowImv];
//                
//                UILabel  *shadowLab = [[UILabel  alloc] initWithFrame:CGRectMake(10, 25, shadowImv.frame.size.width - 20, 20)];
//                shadowLab.text = [tempDic  objectForKey:@"title"];
//                shadowLab.font = [UIFont  systemFontOfSize:14.];
//                shadowLab.textColor = [UIColor  whiteColor];
//                shadowLab.textAlignment = NSTextAlignmentCenter;
//                [shadowImv  addSubview:shadowLab];
//            }
            
            
            imageView.userInteractionEnabled = YES;
            UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(topPicSingleTapAction:)];
            [imageView addGestureRecognizer:singleTap];
            [picScrollView  addSubview:imageView];
        }
        picScrollView.contentOffset = CGPointMake(scrollWidth, 0);
        
        if (picCount >= 2) {
            scrollTimer = [NSTimer  scheduledTimerWithTimeInterval:3.0f target:self selector:@selector(scrollTimerAction) userInfo:nil repeats:YES];
        }
        
    }
    
    pageControl.currentPage = 0;
    
}

//NSTimer Action
- (void)scrollTimerAction
{
    [picScrollView  setContentOffset:CGPointMake((pageControl.currentPage + 2) * picScrollView.frame.size.width, 0) animated:YES];
}

#pragma mark - 轮播图点击
//图片点击
- (void)topPicSingleTapAction:(UITapGestureRecognizer *)recognizer
{
    UIImageView  *tempImv = (UIImageView  *)[recognizer  view];
    if ([self.cirScrollViewDelegate  respondsToSelector:@selector(circleImageDidClick:)]) {
        [self.cirScrollViewDelegate  circleImageDidClick:tempImv.tag - PictureDefaultTag];
    }

}

#pragma mark - UIScrollView Delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat  scrollWidth = scrollView.frame.size.width;
    if (scrollView.contentOffset.x <= 0) {
        [scrollView  setContentOffset:CGPointMake(scrollWidth * allPage, 0) animated:NO];
    }else if (scrollView.contentOffset.x >= scrollWidth * (allPage + 1)){
        [scrollView  setContentOffset:CGPointMake(scrollWidth, 0) animated:NO];
    }
    pageControl.currentPage = (int)(scrollView.contentOffset.x / scrollWidth - 1);
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (scrollTimer) {
        [scrollTimer  invalidate];
        scrollTimer = nil;
    }
    scrollTimer = [NSTimer scheduledTimerWithTimeInterval:3.0f target:self selector:@selector(scrollTimerAction) userInfo:nil repeats:YES];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if (scrollTimer) {
        [scrollTimer invalidate];
        scrollTimer = nil;
    }
}

#pragma mark 前后台切换
- (void)applicationDidEnterBackground
{
    if (scrollTimer) {
        [scrollTimer invalidate];
        scrollTimer = nil;
    }
}

- (void)applicationWillEnterForeground
{
    if (scrollTimer) {
        [scrollTimer  invalidate];
        scrollTimer = nil;
    }
    NSInteger  picCount = showPicArr.count;
    if (picCount >= 2) {
        scrollTimer = [NSTimer scheduledTimerWithTimeInterval:3.0f target:self selector:@selector(scrollTimerAction) userInfo:nil repeats:YES];
    }
}

- (void)dealloc
{
    [[NSNotificationCenter  defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter  defaultCenter] removeObserver:self name:UIApplicationWillEnterForegroundNotification object:nil];
    if (scrollTimer) {
        [scrollTimer  invalidate];
        scrollTimer = nil;
    }
}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
